/*
 * auth:Lyle lylechen2014@gmail.com
 * git:https://gitee.com/copperpeas/wx-bluetooth
 */


const app = getApp()
var util = require('../../utils/util.js');

var time = 0;
var imageData = [];
var k = 0;
var strArray;

var toArrayBuffer = require('to-array-buffer');
var Buffer = require('buffer/').Buffer;

import drawQrcode from '../../utils/weapp.qrcode.esm.js'

import { Base64} from 'js-base64' //比较喜欢这种写法
console.log(Base64);

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

function strToBinary(str) {
  var result = [];
  var list = str.split("");
  for (var i = 0; i < list.length; i++) {
    if (i != 0) {
      result.push(" ");
    }
    var item = list[i];
    var binaryStr = item.charCodeAt().toString(2);
    if (binaryStr) {
      result.push(binartStr);
    }
  }
  return result.join("");
}

Page({
  data: {

    devices: [],
    connected: false,
    chs: [],
  },
  //初始化蓝牙模块
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      },
      fail: (res) => {
        console.log('error:getBluetoothAdapterState', res)
      }
    })
  },
  //开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
      fail: (res) => {
        console.log("搜索蓝牙失败");
      }
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },

  //寻找到新设备的事件的回调函数
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },

  //连接低功耗蓝牙设备
  createBLEConnection(e) {

    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      },
      fail: (res) => {
        console.log("蓝牙连接失败:", res);
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },

  //获取蓝牙设备所有服务(service)
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      },
      fail: (res) => {
        console.log("获取蓝牙服务失败：" + JSON.stringify(res))
      }
    })
  },
  //获取蓝牙设备某个服务中所有特征值(characteristic)
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('获取特征值失败：', res)
      }
    })
    
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },

  //写入打印机
  writeBLECharacteristicValue() {
    let arrPrint = [];
    //初始化打印机
    arrPrint.push(util.sendDirective([0x1B,0x40])); //16进制
    //arrPrint.push(util.hexStringToBuff([27,64])); //10进制
    //居中对齐
    arrPrint.push(util.sendDirective([0x1B,0x61,0x01])); //16进制
    //arrPrint.push(util.hexStringToBuff([27,97,1]));//10进制
    //正文
    arrPrint.push(util.hexStringToBuff("采购单\n"));
    arrPrint.push(util.hexStringToBuff("\n"));
    arrPrint.push(util.hexStringToBuff("2019-08-10 12:45:36\n"));
    arrPrint.push(util.hexStringToBuff("-------------------\n"));
    arrPrint.push(util.hexStringToBuff("大白菜        5千克\n"));
    arrPrint.push(util.hexStringToBuff("-------------------\n"));
    arrPrint.push(util.hexStringToBuff("总计:         5千克\n"));
    arrPrint.push(util.hexStringToBuff("\n"));
    arrPrint.push(util.hexStringToBuff("\n"));
    this.printInfo(arrPrint);
  },
  
  //遍历发送数据
  printInfo:function(arr) {
    var tthis = this;
    if (arr.length > 0) {
      this.sendStr(arr[0], function (success) {
        arr.shift();
        tthis.printInfo(arr);
      }, function (error) {
        console.log(error);
      });
    }
  },

  //断开与低功耗蓝牙设备的连接
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  
  //关闭蓝牙模块
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  
  //发送数据
  sendStr: function (bufferstr, success, failed) {
    var that = this;
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: bufferstr,
      success: function (res) {
        success(res);
        console.log('发送的数据：' + bufferstr)
        console.log('message发送成功')
      },
      failed: function (res) {
        fail(res)
        console.log("数据发送失败:" + JSON.stringify(res))
      },
      complete: function (res) {
        console.log("发送完成:" + JSON.stringify(res))
      }
    })
  },
  
  printImgT() {
    let tthis = this;
    const ctx = wx.createCanvasContext('canvas');
    ctx.clearRect(0, 0, 160, 160);
    drawQrcode({
      canvasId: 'canvas',
      text: String('test'),
      width: 160,
      height: 160,
      callback(e) {
        setTimeout(() => {
          // 获取图片数据
          wx.canvasGetImageData({
            canvasId: 'canvas',
              x: 0,
              y: 0,
              width: 160,
              height: 160,
              success(res) {
                let arr = tthis.convert4to1(res.data);
                let data = tthis.convert8to1(arr);
                const cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 20, 0, 160, 0], data, [27, 74, 3], [27, 64]);
                const buffer = toArrayBuffer(Buffer.from(cmds, 'gb2312'));
                let arrPrint = [];
                arrPrint.push(util.sendDirective([0x1B,0x40])); 
                for (let i=0; i < buffer.byteLength;i=i+20) {
                  arrPrint.push(buffer.slice(i, i+20));
                }
                arrPrint.push(util.sendDirective([0x1B,0x40])); 
                arrPrint.push(util.hexStringToBuff("\n"));
                arrPrint.push(util.hexStringToBuff("\n"));
                tthis.printCode(arrPrint);
              }
          })
        }, 3000);
      }
    }); 
  },
  
  printImg() {
    let tthis = this;
    wx.getImageInfo({
      src: 'http://hqn.fun:9999/code.png',
      success: function(ret) {
        setTimeout(() => {
          var path = ret.path;
          var canvas = wx.createCanvasContext('shareCanvas')
          canvas.drawImage(path, 0, 0, 160, 160);
          canvas.draw()
          console.log(path)
          wx.canvasGetImageData({
            canvasId: 'shareCanvas',
            x: 0,
            y: 0,
            width: 160,
            height: 160,
            success(res) {
              let arr = tthis.convert4to1(res.data);
              let data = tthis.convert8to1(arr);
              const cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 20, 0, 160, 0], data, [27, 74, 3], [27, 64]);
              const buffer = toArrayBuffer(Buffer.from(cmds, 'gb2312'));
              let arrPrint = [];
              arrPrint.push(util.sendDirective([0x1B,0x40]));
              for (let i=0; i < buffer.byteLength;i=i+20) {
                arrPrint.push(buffer.slice(i, i+20));
              }
              arrPrint.push(util.sendDirective([0x1B,0x40])); //16进制
              arrPrint.push(util.hexStringToBuff("\n"));
              arrPrint.push(util.hexStringToBuff("\n"));
              tthis.printCode(arrPrint);
            },
            fail: function(error) {
              console.log("error:" + error);
            }
          })
        }, 3000);
      },
    })
  },
  
  //遍历发送数据
  printCode:function(arr) {
    var tthis = this;
    if (arr.length > 0) {
      this.sendStr(arr[0], function (success) {
        arr.shift();
        tthis.printCode(arr);
      }, function (error) {
        console.log(error);
      });
    }
  },
  
  //4合1 
  convert4to1(res) {
    let arr=[];
    for (let i = 0; i < res.length; i++) {
      if (i % 4 == 0) {
        let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
        if (rule > 200) {
          res[i] = 0;
        } else {
          res[i] = 1;
        }
        arr.push(res[i]);
      }
    }
    return arr;
  },
  
  //8合1
  convert8to1(arr) {
    let data = [];
    for (let k = 0; k < arr.length; k += 8) {
      let temp = arr[k] * 128 + arr[k + 1] * 64 + arr[k + 2] * 32 + arr[k + 3] * 16 + arr[k + 4] * 8 + arr[k + 5] * 4 + arr[k + 6] * 2 + arr[k + 7] * 1
      data.push(temp);
    }
    return data;
  }

  
})